package com.lee.security.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.lee.vo.ResponseVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author Lee HN
 * @date 2019/6/24 14:13
 * 用于response统一处理
 */
@Component
public class ResponseExport {

    @Autowired
    private ObjectMapper objectMapper;

    public void success(HttpServletResponse response, Object data) throws IOException {
        common(response, HttpStatus.OK.value(), ResponseVO.success(data));
    }

    public void failure(HttpServletResponse response, int httpStatus, int statusCode, String message) throws IOException {
        common(response, httpStatus, ResponseVO.failure(statusCode, message));
    }

    private void common(HttpServletResponse response, int httpStatus, ResponseVO responseVO) throws IOException {
        String json = objectMapper.writeValueAsString(responseVO);
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        response.getWriter().write(json);
        response.setStatus(httpStatus);
        //OriginUtil.OriginProcess(response);
    }
}
